/*****************************************************************************************
**  Author:jxx 2022
**  QQ:283591387
**完整文档见：http://v2.volcore.xyz/document/api 【代码生成页面ViewGrid】
**常用示例见：http://v2.volcore.xyz/document/vueDev
**后台操作见：http://v2.volcore.xyz/document/netCoreDev
*****************************************************************************************/
//此js文件是用来自定义扩展业务代码，可以扩展一些自定义页面或者重新配置生成的代码
// import modelHeader from "./purchase.vue"
import modelBody from "./purchaseList.vue"
import modelHeader from "../q_purchase_wjs/q_purchase_wjs.vue" 
import gridHeader from "@/components/print/selectTemplet.vue"

let extension = {
  components: {
    //查询界面扩展组件
    gridHeader,
    gridBody: '',
    gridFooter: '',
    //新建、编辑弹出框扩展组件
    modelHeader: modelHeader,
    modelBody,
    modelFooter: ''
  },
  tableAction: '', //指定某张表的权限(这里填写表名,默认不用填写)
  buttons: { view: [], box: [], detail: [] }, //扩展的按钮
  methods: {
    //下面这些方法可以保留也可以删除
    async onInit() {
      this.queryFields=['AuditStatus','CreateDate']
      this.maxBtnLength = 6;
      this.textInline = false
      this.detailOptions.textInline = false
      let startTime = await this.base.getOneWeekAgoDate()
      let endTime = await this.base.getDate(false) + " 23:59:59"
      this.searchFormFields.CreateDate = [startTime, endTime]

      if (this.$route.path == "/q_purchase_payment" && JSON.stringify(this.$route.query) != '{}') {
        console.log("触发查询")
        await this.base.setSearchParamFn(this)
        // this.searchFormFields.Voucher_sub = null
        // this.searchFormFields.AuditStatus = null
        // this.searchFormFields.CreateDate = [null, null]
        // const selectList = ['Voucher_sub',]
        // this.searchFormOptions.forEach(item => {
        //   item.forEach(x => {
        //     if (!selectList.includes(x.field)) {
        //       x.onChange = (v) => {
        //         this.$route.query = {}
        //       }
        //     }
        //   })
        // })
        setTimeout(() => {
          this.refresh()
        })
      }
    },
    onInited() {
      // this.setFiexdSearchForm(true);
      let indexNum = this.detailOptions.buttons.findIndex(item => item.name == "添加行")
      if (indexNum != "-1") {
        this.detailOptions.buttons.splice(indexNum, 1)
      }
      this.detailOptions.beginEdit = (row, column, index) => {
        if (this.rowAuditStatus != 0) return false;//|| !this.CreateUserBoole
        return true

      }
      this.detailOptions.buttons.unshift({
        name: "选择采购单",
        icon: 'el-icon-plus',
        type: 'primary',
        plain: true,
        onClick: function () {
          this.$store.commit("setTabelText", true)
          if (!this.editFormFields.WHSE_no) {
            this.base.ElMessageFn("请选择采购机构")
            return false;
          }
          this.$refs.modelHeader.open(this.editFormFields.WHSE_no)
        }
      })
    },
    detailFn() {
      console.log(1)
      const item = setInterval(() => {
        let rows = document.querySelectorAll(".grid-detail .el-table__body .el-table__row")
        // this.rowschild = rows[0].childNodes[1]
        console.log("rows", rows);
        if (rows.length) {
          clearInterval(item);
          rows.forEach(item => {
            // 采购单编码
            let testInputDom = item.querySelectorAll("td")[2].querySelector("span")
            console.log("testInputDom", testInputDom);
            testInputDom.style.cursor = "pointer"
            testInputDom.style.color = "#2d8cf0"
            testInputDom.addEventListener("click", (e) => {
              const sub = e.target.innerText
              console.log("sub", sub);
              this.$refs.modelBody.open(sub)

            })
          })
        }
      }, 0)
    },
    async searchBefore(param) {
      //界面查询前,可以给param.wheres添加查询参数
      //返回false，则不会执行查询
      if (this.$route.path != "/q_purchase_payment") {
        param.wheres = param.wheres.filter(item => item.name != "Purchase_payment")
        this.$route.query = {}
      }
      if (this.$route.path == "/q_purchase_payment" && JSON.stringify(this.$route.query) != '{}') {
        await this.base.setSearchBefore(this, "Purchase_payment", param)
        // const sectionState = ["[null,null]", JSON.stringify(["", null]), JSON.stringify([null, ""]), JSON.stringify(["", ""])]
        // const dateState = sectionState.includes(JSON.stringify(this.searchFormFields.CreateDate))
        // if (this.searchFormFields.Voucher_sub || !dateState) {
        //   param.wheres = param.wheres.filter(item => item.name != "Purchase_payment")
        //   this.$route.query = {}
        // }
      }
      return true;
    },
    searchAfter(result) {
      //查询后，result返回的查询数据,可以在显示到表格前处理表格的值
      return true;
    },
    delBefore(ids, rows) { //查询界面的表删除前 ids为删除的id数组,rows删除的行
      let auditStatus = rows.some(x => { return x.AuditStatus == 1 });
      if (auditStatus) {
        this.base.ElMessageFn('不支持删除审核通过数据')
        return false;
      }
      return true;
    },
    addBeforeAsync(formData) {
      return this.testAdd(formData)
    },
    updateBeforeAsync(formData) {
      return this.testAdd(formData)
    },
    rowClick({ row, column, event }) {
      //查询界面点击行事件
      this.$refs.table.$refs.table.toggleRowSelection(row);
    },
    async modelOpenBefore(row) {
      this.$store.commit("setTabelText", false)
      this.CreateUserBoole = row.CreateID == this.$store.state.userID
      this.rowAuditStatus = await row.AuditStatus
      if (JSON.stringify(row) == "{}") {
        this.rowAuditStatus = 0
        this.CreateUserBoole = true
      }
      if (this.$route.path != "/q_purchase_payment" || this.rowAuditStatus != 0) {//|| !this.CreateUserBoole
        this.boxButtons[0].hidden = true
        this.detailOptions.buttons.forEach(item => {
          if (item.name != "导出" && item.name != "刷新") {
            item.hidden = true
          }
        })
      } else {
        this.boxButtons[0].hidden = false
        this.detailOptions.buttons.forEach(item => item.hidden = false)
      }
    },
    modelOpenAfter(row) {
      if (this.currentAction != 'Add') {
        this.detailFn()
      }else{
        this.editFormFields.Payment_status = '0';
      }
      this.editFormOptions.forEach(item => {
        item.forEach(x => {
          if (x.title == "付款状态") {
            x.hidden = true
          }
          x.disabled = false
          if (x.field == "WHSE_no") {
            x.onChange = () => {
              console.log("采购机构")
              this.$refs.detail.rowData = []
            }
          }
          if (x.field != "Remark"&&x.field != "WHSE_no") { // || !this.CreateUserBoole
            x.disabled = true
          }
          if (this.$route.path != "/q_purchase_payment" || this.rowAuditStatus != 0) { //|| !this.CreateUserBoole
            x.disabled = true
           }
        })
      })
      // if (this.currentAction != 'Add') {
      //   // 跳去采购单页面
      //   const item = setInterval(() => {
      //     let rows = document.querySelectorAll(".grid-detail .el-table__body .el-table__row")
      //     // this.rowschild = rows[0].childNodes[1]
      //     // console.log("rows", rows);
      //     if (rows.length) {
      //       clearInterval(item);
      //       rows.forEach(item => {
      //         // 采购单编码
      //         let testInputDom = item.querySelectorAll("td")[1].querySelector("span")
      //         // console.log("testInputDom", testInputDom);
      //         testInputDom.style.cursor = "pointer"
      //         testInputDom.style.color = "#2d8cf0"
      //         testInputDom.addEventListener("click", (e) => {
      //           const sub = e.target.innerText
      //           this.$refs.modelBody.open(sub)

      //         })
      //       })
      //     }

      //   }, 500)
      // }

    },
    detailRowClick({ row, column, event }) {
      this.$refs.detail.$refs.table.toggleRowSelection(row);
      if (this.rowAuditStatus != 0) return;//|| !this.CreateUserBoole
      if (column.property == "Paid_price" || column.property == "Remark"||column.property =="adjustRemark"||column.property =="adjust") {
        let dom = event.target
        if (dom.nodeName != "SPAN") {
          setTimeout(() => {
            let inpDom = dom.querySelector("input")
            inpDom.focus()
          }, 0)
        }
      }
    },
    onModelClose(iconClick) {
      //iconClick=true为点击左中上角X触发的关闭事件
      //如果返回 false不会关闭弹出框 
      //return false;
      // this.storeRemoveForm()
      this.$store.commit("setTabelText", true)
      this.boxModel = false;
    },
    async testAdd(formData) {
      if (!this.$refs.detail.rowData.length) {
        this.base.ElMessageFn('明细表不可为空', "error")
        return false
      }
      if (!this.editFormFields.WHSE_no) {
        this.base.ElMessageFn('请选择采购机构')
        return false
      }
      

      // let boole2 = formData.detailData.some(item => +item.Paid_price === 0 )
      // if (boole2) {
      //   this.base.ElMessageFn("明细表中实付金额不可为零或空")
      //   return false;
      // }
      let boole = formData.detailData.some(item => (item.Paid_price == "" || item.Paid_price == null || item.Paid_price == undefined)&&item.Paid_price!="0")
      if (boole) {
        this.base.ElMessageFn("明细表中请填写实付金额")
        return false;
      }
      let boole3 = formData.detailData.every(item => +item.Paid_price >= 0 )
      if (!boole3) {
        this.base.ElMessageFn("明细表中实付金额请填写有效正数")
        return false;
      }

     
      let boole22 = formData.detailData.some(item => item.adjust === ""||item.adjust === null||item.adjust === undefined||(""+item.adjust).trim()==="")
      if (boole22) {
        this.base.ElMessageFn("明细表中调整金额不可为空")
        return false;
      }
      let boole33 = formData.detailData.every(item =>+item.adjust >=0||+item.adjust < 0)
      if (!boole33) {
        this.base.ElMessageFn("明细表中调整金额请填写有效数字")
        return false;
      }
      let boole4 = formData.detailData.every(item => +item.Paid_price  <= (+item.adjust + +item.Unpaidamount))
      if (!boole4) {
        this.base.ElMessageFn("实付金额不可大于未付款金额和调整金额总和")
        return false;
      }

    
      let booleP3 = formData.detailData.every(item => (+item.PaymentType>=0&&item.PaymentType!==""&&item.PaymentType!==null))
      // let booleP4 = formData.detailData.some(item => !item.Supplier)
      if (!booleP3) {
        this.base.ElMessageFn("明细单中请选择付款方式")
        return false;
      }
      // if (booleP4) {
      //   this.base.ElMessageFn("明细单中请选择供应商")
      //   return false;
      // }
      return true
    },
  }
};
export default extension;
